import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, logout as apiLogout, getCurrentUser, register as apiRegister } from '@/api/auth'
import type { UserInfo, RegisterRequest } from '@/api/auth'
import { Notify } from '@opentiny/vue'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<UserInfo | null>(null)
  const isAuthenticated = computed(() => !!token.value)

  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setUser = (userData: UserInfo) => {
    user.value = userData
    localStorage.setItem('user', JSON.stringify(userData))
  }

  const clearAuth = () => {
    token.value = null
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  const login = async (credentials: { username: string; password: string }) => {
    try {
      const response = await apiLogin(credentials)
      
      if (response.code === 200 && response.token && response.user) {
        setToken(response.token)
        setUser(response.user)
        
        Notify({ type: 'success', message: '登录成功', position: 'top-right' })
        return { success: true, data: { token: response.token, user: response.user } }
      } else {
        const errorMsg = response.msg || '登录失败'
        Notify({ type: 'error', message: errorMsg, position: 'top-right' })
        return { success: false, error: errorMsg }
      }
    } catch (error: any) {
      console.error('Login failed:', error)
      const errorMsg = error?.message || '登录失败，请稍后重试'
      Alert({ message: errorMsg, type: 'error' })
      return { success: false, error: errorMsg }
    }
  }

  const register = async (registerData: RegisterRequest) => {
    try {
      const response = await apiRegister(registerData)
      
      if (response.code === 200) {
        Notify({ type: 'success', message: '注册成功', position: 'top-right' })
        return { success: true, data: response.data }
      } else {
        const errorMsg = response.msg || '注册失败'
        Notify({ type: 'error', message: errorMsg, position: 'top-right' })
        return { success: false, error: errorMsg }
      }
    } catch (error: any) {
      console.error('Register failed:', error)
      const errorMsg = error?.message || '注册失败，请稍后重试'
      Message.error(errorMsg)
      return { success: false, error: errorMsg }
    }
  }

  const logout = async () => {
    try {
      await apiLogout()
      clearAuth()
      Notify({ type: 'success', message: '退出成功' })
      
      // 重定向到登录页面
      window.location.href = '/login'
    } catch (error) {
      console.error('Logout failed:', error)
      clearAuth()
      window.location.href = '/login'
    }
  }

  const checkAuth = async () => {
    const savedToken = localStorage.getItem('token')

    if (!savedToken) {
      clearAuth()
      return false
    }

    try {
      // 验证token并获取最新用户信息
      setToken(savedToken)
      const response = await getCurrentUser()
      
      if (response.code === 200 && response.data) {
        setUser(response.data)
        return true
      } else {
        clearAuth()
        return false
      }
    } catch (error) {
      console.error('Token validation failed:', error)
      clearAuth()
      return false
    }
  }

  // TODO: 权限系统待实现
  const hasPermission = (permission: string): boolean => {
    // 临时实现：基于用户状态判断基础权限
    return user.value?.status === 1 || false
  }

  const hasRole = (role: string): boolean => {
    // TODO: 实现角色系统
    return true
  }

  const updateProfile = async (profileData: Partial<UserInfo>) => {
    if (!user.value) return { success: false, error: '用户未登录' }

    try {
      // TODO: 调用更新用户资料API
      const updatedUser = { ...user.value, ...profileData }
      setUser(updatedUser)
      Notify({ type: 'success', message: '资料更新成功' })
      return { success: true }
    } catch (error: any) {
      console.error('Profile update failed:', error)
      const errorMsg = error?.message || '更新失败'
      Message.error(errorMsg)
      return { success: false, error: errorMsg }
    }
  }

  return {
    token,
    user,
    isAuthenticated,
    setToken,
    setUser,
    clearAuth,
    login,
    register,
    logout,
    checkAuth,
    hasPermission,
    hasRole,
    updateProfile
  }
})